// --------------------------------------------------------------------------------------------------------------------
// <copyright file="SampleTrafficLightsFSMTest.cs" company="Microsoft Corporation">
// The MIT License (MIT)
// 
// Copyright (c) 2014, Microsoft Corporation
// 
// Permission is hereby granted, free of charge, to any person obtaining a copy
//  of this software and associated documentation files (the "Software"), to deal
//  in the Software without restriction, including without limitation the rights
//  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
//  copies of the Software, and to permit persons to whom the Software is
//  furnished to do so, subject to the following conditions:
// 
// The above copyright notice and this permission notice shall be included in
//  all copies or substantial portions of the Software.
// 
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
//  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
//  THE SOFTWARE.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------

namespace Microsoft.Robotics.Core.UnitTests
{
    using System;
    using Microsoft.Robotics.FiniteStateMachine;
    using Microsoft.VisualStudio.TestTools.UnitTesting;

    /// <summary>
    /// Finite state machine tests.
    /// </summary>
    /// <remarks>
    /// A traffic light system with two directions of traffic given red/yellow/green lights.
    /// Through traffic is given priority unless there is Crossing traffic Waiting (detected
    /// by a pressure plate under the pavement presumably).
    /// </remarks>
    [TestClass]
    public class SampleTrafficLightsFSMTests
    {
        /// <summary>
        /// Test state machine mechanics using traffic light system.
        /// </summary>
        [TestMethod]
        [TestCategory("Unit")]
        public void TrafficLightsFSMTest()
        {
            var traffic = new Traffic();

            // initially thru traffic flowing
            Assert.AreEqual("State: ThruTrafficFlowing Context: False Green Red 0", traffic.ToString());

            // still after 100 seconds
            ElapsedTime(100, traffic);
            Assert.AreEqual("State: ThruTrafficFlowing Context: False Green Red 100", traffic.ToString());

            // crossing traffic now wating at the intersection (give thru traffic a yellow light)
            traffic.CrossTraffic(true);
            Assert.AreEqual("State: StoppingThruTraffic Context: True Yellow Red 0", traffic.ToString());

            // crossing traffic gets to go after 10 seconds
            ElapsedTime(10, traffic);
            Assert.AreEqual("State: CrossTrafficFlowing Context: True Red Green 0", traffic.ToString());

            // cross traffic stopped after 20 sec.
            ElapsedTime(20, traffic);
            Assert.AreEqual("State: StoppingCrossTraffic Context: True Red Yellow 0", traffic.ToString());

            // through traffic continues after 10 more sec.
            ElapsedTime(10, traffic);
            Assert.AreEqual("State: ThruTrafficFlowing Context: True Green Red 0", traffic.ToString());

            // through traffic stops again after 20 sec.
            ElapsedTime(20, traffic);
            Assert.AreEqual("State: StoppingThruTraffic Context: True Yellow Red 0", traffic.ToString());

            // cross traffic goes again after 10 sec.
            ElapsedTime(10, traffic);
            Assert.AreEqual("State: CrossTrafficFlowing Context: True Red Green 0", traffic.ToString());
            
            // cross traffic stopped again after 20 sec.
            ElapsedTime(20, traffic);
            Assert.AreEqual("State: StoppingCrossTraffic Context: True Red Yellow 0", traffic.ToString());
            
            // through traffic continues again after 10 more sec.
            ElapsedTime(10, traffic);
            Assert.AreEqual("State: ThruTrafficFlowing Context: True Green Red 0", traffic.ToString());
            
            // through traffic continues indifinitely while no cross traffic waiting
            traffic.CrossTraffic(false);
            ElapsedTime(100, traffic);
            Assert.AreEqual("State: ThruTrafficFlowing Context: False Green Red 100", traffic.ToString());
        }

        /// <summary>
        /// Cause time to elapse.
        /// </summary>
        /// <param name="ticks">Number of ticks to elapse.</param>
        /// <param name="traffic">Traffic FSM.</param>
        private static void ElapsedTime(int ticks, Traffic traffic)
        {
            for (var i = 0; i < ticks; i++)
            {
                traffic.Tick();
            }
        }

        /// <summary>
        /// Context for traffic lights system.
        /// </summary>
        public class Lights : IContext<Lights.LightsInput, Lights.LightsOutput>
        {
            /// <summary>
            /// Initializes a new instance of the Lights class.
            /// </summary>
            /// <param name="through">Color of through-traffic light.</param>
            /// <param name="crossing">Color of crossing-traffic light.</param>
            public Lights(Color through, Color crossing)
            {
                this.Input = new LightsInput();
                this.Output = new LightsOutput();
                this.ChangeColors(through, crossing);
            }

            /// <summary>
            /// Light color.
            /// </summary>
            public enum Color
            {
                /// <summary>
                /// Red traffic light (nothing more to say, but StyleCop makes me do this).
                /// </summary>
                Red,

                /// <summary>
                /// Yellow traffic light.
                /// </summary>
                Yellow,

                /// <summary>
                /// Green traffic light.
                /// </summary>
                Green
            }

            /// <summary>
            /// Gets or sets Input values.
            /// </summary>
            public LightsInput Input { get; set; }

            /// <summary>
            /// Gets or sets Output values.
            /// </summary>
            public LightsOutput Output { get; set; }

            /// <summary>
            /// Gets or sets the number of seconds elapsed.
            /// </summary>
            public int Seconds { get; set; }

            /// <summary>
            /// Change state of the lights.
            /// </summary>
            /// <param name="through">Color of through-traffic light.</param>
            /// <param name="crossing">Color of crossing-traffic light.</param>
            /// <returns>Updated state.</returns>
            public Lights ChangeColors(Color through, Color crossing)
            {
                this.Output.Through = through;
                this.Output.Crossing = crossing;
                this.Seconds = 0;
                return this;
            }

            /// <summary>
            /// String representation of context (for testing).
            /// </summary>
            /// <returns>String representation.</returns>
            public override string ToString()
            {
                return string.Format("{0} {1} {2} {3}", this.Input.Waiting, this.Output.Through, this.Output.Crossing, this.Seconds);
            }

            /// <summary>
            /// Input context values.
            /// </summary>
            public class LightsInput
            {
                /// <summary>
                /// Gets or sets a value indicating whether cross traffic is waiting.
                /// </summary>
                public bool Waiting { get; set; }
            }

            /// <summary>
            /// Output context values.
            /// </summary>
            public class LightsOutput
            {
                /// <summary>
                /// Gets or sets a values indicating whether through traffic is flowing.
                /// </summary>
                public Color Through { get; set; }

                /// <summary>
                /// Gets or sets a value indicating whether cross traffic is flowing.
                /// </summary>
                public Color Crossing { get; set; }
            }
        }

        /// <summary>
        /// Traffic lights state machine.
        /// </summary>
        public class Traffic : Machine<Lights.LightsInput, Lights.LightsOutput, Lights>
        {
            /// <summary>
            /// Initializes a new instance of the Traffic class.
            /// </summary>
            public Traffic()
            {
                // states
                var thruTrafficFlowing = new State<Lights>(
                    "ThruTrafficFlowing",
                    s => s.ChangeColors(Lights.Color.Green, Lights.Color.Red));
                    
                var stoppingThruTraffic = new State<Lights>(
                    "StoppingThruTraffic",
                    s => s.ChangeColors(Lights.Color.Yellow, Lights.Color.Red));
                    
                var crossTrafficFlowing = new State<Lights>(
                    "CrossTrafficFlowing",
                    s => s.ChangeColors(Lights.Color.Red, Lights.Color.Green));
                    
                var stoppingCrossTraffic = new State<Lights>(
                    "StoppingCrossTraffic",
                    s => s.ChangeColors(Lights.Color.Red, Lights.Color.Yellow));

                // transitions
                const int MaxRed = 20;
                const int MaxYellow = 10;
         
                thruTrafficFlowing.AddTransition( // Stopping thru traffic for waiting cross traffic.
                    s => s.Input.Waiting && s.Seconds >= MaxRed,
                    stoppingThruTraffic);
                    
                stoppingThruTraffic.AddTransition( // Let cross traffic go.
                    s => s.Seconds >= MaxYellow,
                    crossTrafficFlowing);
         
                crossTrafficFlowing.AddTransition( // Stopping cross traffic for thru traffic.
                    s => s.Seconds >= MaxRed,
                    stoppingCrossTraffic);
                    
                stoppingCrossTraffic.AddTransition( // Let thru traffic go.
                    s => s.Seconds >= MaxYellow,
                    thruTrafficFlowing);

                this.Initialize(new Lights(Lights.Color.Green, Lights.Color.Red), thruTrafficFlowing);
            }

            /// <summary>
            /// Counts the passage of time.
            /// </summary>
            public void Tick()
            {
                this.Context.Seconds++;
                this.Update(this.Context.Input);
            }
         
            /// <summary>
            /// Pressure pad under the pavement signaling waiting cross-traffic.
            /// </summary>
            /// <param name="waiting">Whether cross-traffic is waiting.</param>
            public void CrossTraffic(bool waiting)
            {
                if (this.Context.Input.Waiting != waiting)
                {
                    this.Context.Input.Waiting = waiting;
                    this.Update(this.Context.Input);
                }
            }

            /// <summary>
            /// String representation of the Machine (for testing).
            /// </summary>
            /// <returns>String representation.</returns>
            public override string ToString()
            {
                return string.Format("State: {0} Context: {1}", this.State.ToString(), this.Context.ToString());
            }
        }
    }
}
